﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;

using YQHL.GS.Model;
using YQHL.GS.Server;

namespace YQHL.GS
{
    /// <summary>
    /// Server
    /// </summary>
    public class AppServer
    {
        /// <summary>
        /// 查询银行流水
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public JArray GetBankData(PageQuery query)
        {
            var rootJObject = new JObject();
            rootJObject["?xml"] = new JObject();
            rootJObject["?xml"]["@version"] = "1.0";
            rootJObject["?xml"]["@encoding"] = "GBK";

            rootJObject["CMS"] = new JObject();
            rootJObject["CMS"]["eb"] = new JObject();
            rootJObject["CMS"]["eb"]["pub"] = new JObject();
            rootJObject["CMS"]["eb"]["in"] = new JObject();
            //初始化JObject
            var pubNode = rootJObject["CMS"]["eb"]["pub"];
            var inNode = rootJObject["CMS"]["eb"]["in"];

            #region 装载基础信息

            pubNode["TransCode"] = "QHISD";
            pubNode["CIS"] = "440290002213490";
            pubNode["BankCode"] = "102";
            pubNode["ID"] = Config.SID;
            pubNode["TranDate"] = DateTime.Now.ToString("yyyyMMdd");
            pubNode["TranTime"] = DateTime.Now.ToString("yyyyMMdd");
            pubNode["fSeqno"] = Guid.NewGuid().ToString().Replace("-", "");// DateTime.Now.ToString("yyyyMMddHHmmssfff");

            #endregion 装载基础信息

            #region 装载查询条件

            inNode["AccNo"] = query.AccNo;
            inNode["BeginDate"] = query.BeginDate.ToString("yyyyMMdd");
            inNode["EndDate"] = query.EndDate.ToString("yyyyMMdd");
            inNode["MinAmt"] = (query.MinAmt * 100).ToString();
            inNode["MaxAmt"] = (query.MaxAmt * 100).ToString();
            inNode["NextTag"] = query.NextTag;
            inNode["ReqReserved1"] = query.ReqReserved1;
            inNode["ReqReserved2"] = query.ReqReserved2;

            #endregion 装载查询条件

            Dictionary<string, string> dir = new Dictionary<string, string>();
            dir.Add("Version", Config.CmpVersion);
            dir.Add("TransCode", pubNode["TransCode"].ToObject<string>());
            dir.Add("BankCode", pubNode["BankCode"].ToObject<string>());
            dir.Add("GroupCIS", pubNode["CIS"].ToObject<string>());
            dir.Add("ID", Config.SID);
            dir.Add("PackageID", pubNode["fSeqno"].ToObject<string>());
            dir.Add("Cert", "");
            dir.Add("Language", Config.Language);
            dir.Add("reqData", Utility.JsonConvertToXml(rootJObject).InnerXml);
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dir)
            {
                if (i > 0)
                {
                    builder.Append("&");
                }
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            string urlStr = "http://" + Config.NCIP + ":" + Config.NCPort + "/servlet/ICBCCMPAPIReqServlet?userID=" + Config.SID + "&PackageID=" + pubNode["fSeqno"].ToObject<string>() + "&SendTime=" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string returnFlag = HttpClient.Send(builder.ToString(), urlStr); //获得http返回码
            returnFlag = returnFlag.Substring(8);
            //这里需要验证签名 暂时未写入验证程序
            var s = new Base64Decoder().GetDecoded(returnFlag);
            System.Text.Encoding encode = System.Text.Encoding.ASCII;//用ASCII的话, 碰到中文就变成乱码了, 要用Default
            byte[] bytedata = encode.GetBytes(returnFlag);
            var d = Convert.FromBase64String(returnFlag);
            var resonStr = System.Text.Encoding.GetEncoding("GBK").GetString(d);

            var resonObj = Utility.XmlConvertJson(resonStr);
            if (resonObj["CMS"]["eb"]["pub"]["RetCode"].ToObject<string>() != "0")
            {
                //抛出异常
                throw new Exception(resonObj["CMS"]["eb"]["pub"]["RetMsg"].ToObject<string>());
            }
            var reson = resonObj["CMS"]["eb"]["out"]["rd"] as JArray;

            if (resonObj["CMS"]["eb"]["out"]["NextTag"].ToObject<string>() != "" && resonObj["CMS"]["eb"]["out"]["NextTag"].ToObject<string>() != null)
            {
                query.NextTag = resonObj["CMS"]["eb"]["out"]["NextTag"].ToObject<string>();
                foreach (var item in GetBankData(query))
                {
                    reson.Add(item);
                }
            }
            return reson;
        }

        /// <summary>
        /// 查询银行余额（多账号）
        /// </summary>
        /// <param name="accountArry">用户名Arry</param>
        /// <returns></returns>
        [Obsolete("未实现")]
        public JArray GetAccountCent(List<string> accountArry)
        {
            return null;
        }

        /// <summary>
        /// 查询银行余额（单账号）
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public JObject GetAccountCent(string account)
        {
            var rootJObject = new JObject();
            rootJObject["?xml"] = new JObject();
            rootJObject["?xml"]["@version"] = "1.0";
            rootJObject["?xml"]["@encoding"] = "GBK";

            rootJObject["CMS"] = new JObject();
            rootJObject["CMS"]["eb"] = new JObject();
            rootJObject["CMS"]["eb"]["pub"] = new JObject();
            rootJObject["CMS"]["eb"]["in"] = new JObject();
            //初始化JObject
            var pubNode = rootJObject["CMS"]["eb"]["pub"];
            var inNode = rootJObject["CMS"]["eb"]["in"];

            #region 装载基础信息

            pubNode["TransCode"] = "QACCBAL";
            pubNode["CIS"] = "440290002213490";
            pubNode["BankCode"] = "102";
            pubNode["ID"] = Config.SID;
            pubNode["TranDate"] = DateTime.Now.ToString("yyyyMMdd");
            pubNode["TranTime"] = DateTime.Now.ToString("yyyyMMdd");
            pubNode["fSeqno"] = DateTime.Now.ToString("yyyyMMddHHmmssfff");

            #endregion 装载基础信息

            #region 装载查询条件

            inNode["TotalNum"] = 1;
            inNode["ReqReserved1"] = "";
            inNode["ReqReserved2"] = "";
            inNode["rd"] = new JObject();
            inNode["rd"]["iSeqno"] = pubNode["fSeqno"].ToObject<string>();
            inNode["rd"]["AccNo"] = account;
            inNode["rd"]["CurrType"] = "001";
            inNode["rd"]["ReqReserved3"] = "";
            inNode["rd"]["ReqReserved4"] = "";

            #endregion 装载查询条件

            Dictionary<string, string> dir = new Dictionary<string, string>();
            dir.Add("Version", Config.CmpVersion);
            dir.Add("TransCode", pubNode["TransCode"].ToObject<string>());
            dir.Add("BankCode", pubNode["BankCode"].ToObject<string>());
            dir.Add("GroupCIS", pubNode["CIS"].ToObject<string>());
            dir.Add("ID", Config.SID);
            dir.Add("PackageID", pubNode["fSeqno"].ToObject<string>());
            dir.Add("Cert", "");
            dir.Add("Language", Config.Language);
            dir.Add("reqData", Utility.JsonConvertToXml(rootJObject).InnerXml);
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dir)
            {
                if (i > 0)
                {
                    builder.Append("&");
                }
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            string urlStr = "http://" + Config.NCIP + ":" + Config.NCPort + "/servlet/ICBCCMPAPIReqServlet?userID=" + Config.SID + "&PackageID=" + pubNode["fSeqno"].ToObject<string>() + "&SendTime=" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string returnFlag = HttpClient.Send(builder.ToString(), urlStr); //获得http返回码
            returnFlag = returnFlag.Substring(8);
            //这里需要验证签名 暂时未写入验证程序
            var s = new Base64Decoder().GetDecoded(returnFlag);
            System.Text.Encoding encode = System.Text.Encoding.ASCII;//用ASCII的话, 碰到中文就变成乱码了, 要用Default
            byte[] bytedata = encode.GetBytes(returnFlag);
            var d = Convert.FromBase64String(returnFlag);
            var resonStr = System.Text.Encoding.GetEncoding("GBK").GetString(d);

            var resonObj = Utility.XmlConvertJson(resonStr);
            if (resonObj["CMS"]["eb"]["pub"]["RetCode"].ToObject<string>() != "0")
            {
                //抛出异常
                throw new Exception(resonObj["CMS"]["eb"]["pub"]["RetMsg"].ToObject<string>());
            }
            var reson = resonObj["CMS"]["eb"]["out"]["rd"] as JObject;
            return reson;
        }
    }
}